<?php

namespace Slowlyo\LaravelResponse;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Resources\Json\JsonResource;

class PageResource extends JsonResource
{

    private $ResourceClass = '';

    private $callBack = null;

    public static function collection($resource)
    {
        return static::make($resource);
    }

    public function setResource($resource)
    {
        try {
            ($resource)::make(null);
            $this->ResourceClass = $resource;
        } catch (\Exception $e) {
        }
        return $this;
    }

    public function setCallBack($callback)
    {
        if ($callback instanceof \Closure) {
            $this->callBack = $callback;
        }
        return $this;
    }

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        if ($this->resource instanceof Collection) {
            $this->resource = $this->resource->map($this->itemHandler());
        } else {
            $this->setCollection($this->getCollection()->map($this->itemHandler()));
        }

        $data = parent::toArray($request);
        unset($data['links'], $data['next_page_url'], $data['prev_page_url'], $data['last_page_url'], $data['first_page_url'], $data['form'], $data['to']);
        return $data;
    }

    private function itemHandler()
    {
        return function ($item) {
            if ($this->callBack instanceof \Closure) {
                return call_user_func($this->callBack, $item);
            } else if ($this->ResourceClass) {
                return ($this->ResourceClass)::make($item);
            }
            return $item;
        };
    }
}
